import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  UseGuards,
  Request,
  HttpCode,
  HttpStatus,
  Param,
  ParseIntPipe,
  UseInterceptors,
  UploadedFile,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiConsumes,
} from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { UserService } from './user.service';
import { UploadService } from './upload.service';
import {
  UpdateUserDto,
  UserProfileResponseDto,
  UpdatePasswordDto,
} from './dto/user.dto';

@ApiTags('用户管理')
@Controller('user')
export class UserController {
  constructor(
    private readonly userService: UserService,
    private readonly uploadService: UploadService,
  ) {}

  @Get('profile')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取用户详情' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: UserProfileResponseDto,
  })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  async getUserProfile(@Request() req) {
    const userId = req.user.id;
    const result = await this.userService.getUserProfile(userId);

    return {
      code: 200,
      message: '获取用户信息成功',
      data: result,
      timestamp: Date.now(),
    };
  }

  @Post('update')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '更新用户信息' })
  @ApiResponse({
    status: 200,
    description: '更新成功',
    type: UserProfileResponseDto,
  })
  @ApiResponse({ status: 400, description: '参数错误' })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  async updateUser(@Request() req, @Body() updateDto: UpdateUserDto) {
    const userId = req.user.id;
    const result = await this.userService.updateUser(userId, updateDto);

    return {
      code: 200,
      message: '更新用户信息成功',
      data: result,
      timestamp: Date.now(),
    };
  }

  @Post('upload-avatar')
  @UseGuards(JwtAuthGuard)
  @UseInterceptors(FileInterceptor('file'))
  @ApiBearerAuth()
  @ApiConsumes('multipart/form-data')
  @ApiOperation({ summary: '上传用户头像' })
  @ApiResponse({ status: 200, description: '头像上传成功' })
  @ApiResponse({ status: 400, description: '文件类型不支持或文件过大' })
  @ApiResponse({ status: 401, description: '未授权' })
  @HttpCode(HttpStatus.OK)
  async uploadAvatar(
    @Request() req,
    @UploadedFile() file: Express.Multer.File,
  ) {
    if (!file) {
      return {
        code: 400,
        message: '请选择要上传的头像文件',
        data: null,
        timestamp: Date.now(),
      };
    }

    // 验证是否为图片文件
    const allowedTypes = [
      'image/jpeg',
      'image/jpg',
      'image/png',
      'image/gif',
      'image/webp',
    ];
    if (!allowedTypes.includes(file.mimetype)) {
      return {
        code: 400,
        message: '头像文件必须是图片格式（JPG、PNG、GIF、WebP）',
        data: null,
        timestamp: Date.now(),
      };
    }

    // 验证文件大小（头像限制为5MB）
    const maxSize = 5 * 1024 * 1024; // 5MB
    if (file.size > maxSize) {
      return {
        code: 400,
        message: '头像文件大小不能超过5MB',
        data: null,
        timestamp: Date.now(),
      };
    }

    try {
      // 上传文件
      const uploadResult = await this.uploadService.uploadFile(file);

      // 更新用户头像
      const userId = req.user.id;
      const updateResult = await this.userService.updateUser(userId, {
        avatar: uploadResult.url,
      });

      return {
        code: 200,
        message: '头像上传成功',
        data: {
          avatar: uploadResult.url,
          user: updateResult,
        },
        timestamp: Date.now(),
      };
    } catch (error) {
      return {
        code: 500,
        message: `头像上传失败: ${error.message}`,
        data: null,
        timestamp: Date.now(),
      };
    }
  }

  @Post('update-password')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '更新用户密码' })
  @ApiResponse({ status: 200, description: '密码更新成功' })
  @ApiResponse({ status: 400, description: '参数错误或当前密码不正确' })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  async updatePassword(
    @Request() req,
    @Body() updatePasswordDto: UpdatePasswordDto,
  ) {
    const userId = req.user.id;
    await this.userService.updatePassword(
      userId,
      updatePasswordDto.currentPassword,
      updatePasswordDto.newPassword,
    );

    return {
      code: 200,
      message: '密码更新成功',
      data: null,
      timestamp: Date.now(),
    };
  }

  @Delete('account')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '删除用户账户' })
  @ApiResponse({ status: 200, description: '账户删除成功' })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  async deleteAccount(@Request() req) {
    const userId = req.user.id;
    await this.userService.deleteAccount(userId);

    return {
      code: 200,
      message: '账户删除成功',
      data: null,
      timestamp: Date.now(),
    };
  }

  @Post('points/add/:points')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '增加用户积分（管理员功能）' })
  @ApiResponse({ status: 200, description: '积分增加成功' })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  async addPoints(
    @Request() req,
    @Param('points', ParseIntPipe) points: number,
  ) {
    const userId = req.user.id;
    await this.userService.addPoints(userId, points, '管理员手动添加');

    return {
      code: 200,
      message: `成功增加${points}积分`,
      data: null,
      timestamp: Date.now(),
    };
  }
}
